package com.sh.util;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Component
@PropertySource("classpath:config/sys.properties")
public class UploadImg {

    @Value("${upload.pre}")
     private static String path;

    public static String upload(MultipartFile file1) throws IOException {
        String access = "1_OeHyPTYVyRBVzRDmNJGpJ3WWj6kwr5QCgHyvy7";
        String secret = "RP3h-yZf_N4jqxe5yhwZJaXinTAgh-_sdwr0weEI";
        String bucketName = "weihaujunspce";
       // File file = new File("F:/图片/GIF_1555634853827.gif");
        String fileName="my1.gif";

        Configuration cfg = new Configuration(Zone.autoZone());

        UploadManager uploadManager = new UploadManager(cfg);

        Auth auth = Auth.create(access, secret);
        String upToken = auth.uploadToken(bucketName,fileName);
        // System.out.println("token="+upToken);

       // FileInputStream inputStream = new FileInputStream(file);
       // MultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(inputStream));

        Response response= uploadManager.put(file1.getBytes(),fileName,auth.uploadToken(bucketName));

        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        //DefaultPutRet putRet1 = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        // "qs27mwg5z.hn-bkt.clouddn.com"

        System.out.println("===============");
        String returnPath =  path+ "/" + putRet.key;
        return returnPath;
    }
}
